package tech.yunland.shop.web;


import com.alibaba.fastjson.JSON;
import com.moyuer.bsf.common.Pagination;
import com.moyuer.bsf.domain.model.Role;
import com.moyuer.bsf.domain.model.User;
import com.moyuer.bsf.domain.model.UserRoles;
import com.moyuer.bsf.web.controller.BaseController;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tech.yunland.shop.domain.model.JobPrize;
import tech.yunland.shop.domain.service.JobPrizeService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 职位提成
 *
 * @author 王东阳<350456985@qq.com>
 */
@RestController
@RequestMapping("/job_prize")
public class JobPrizeController extends BaseController {

    @Autowired
    private JobPrizeService jobPrizeService;

    @RequestMapping(value = "/", method = RequestMethod.POST)
    public void saveOrUpdate(@RequestBody JobPrize jobPrize) {

        //输入日志
        logger.info(JSON.toJSONString(jobPrize, true));

        if (jobPrize.getOrganId() == null) {
            jobPrize.setOrganId(primaryOrganId);
        }

        if (jobPrize.getJobId() == null) {
            jobPrize.setJobId(this.currentUserId);
        }

        if (jobPrize.getVer() == null) {
            jobPrize.setVer(0);
        }

        if (jobPrize.getPrizeType() == null) {
            throw new RuntimeException("提成类型不能为空");
        }

        if (jobPrize.getJobId() == null) {
            throw new RuntimeException("职位 id 不能为空");
        }

        if (jobPrize.getPrizeValue() == null) {

            throw new RuntimeException("计提金额不能为空");
        }

        if (jobPrize.getCreator() == null) {
            jobPrize.setCreator(this.currentUser);
        }

        if (jobPrize.getStartDate() == null) {
            throw new RuntimeException("业务时间不能为空");
        }

        if (jobPrize.getJobId() != null) {
            Role job = new Role();
            job.setId(jobPrize.getJobId());
            job.setOrgan(primaryOrgan);

            jobPrize.setJob(job);
        }


        jobPrizeService.saveOrUpdate(jobPrize);

        // 保存日志
        saveLog("保存职位:[" + jobPrizeService.getJobName(jobPrize.getJobId()) + "]提成:[" + jobPrize.getPrizeValue() + "]成功!");
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public JobPrize get(@PathVariable String id) {
        return jobPrizeService.get(id);
    }

    /**
     * 根据 id 标记删除
     *
     * @param id
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public void Delayed(@PathVariable String id) {
        JobPrize jobPrize = jobPrizeService.get(id);
        jobPrizeService.delJobPrize(id);
        saveLog("职位:[" + jobPrize.getJob().getName() + "]提成删除成功！");
    }

    /**
     * 根据入参查询结果集
     *
     * @param creatorId
     * @param
     * @param
     * @return
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public Pagination<JobPrize> getResultInfo(
            @RequestParam(required = false) String jobId,
            @RequestParam(required = false) String creatorId,
            @RequestParam(required = false) Integer state,
            @RequestParam(required = false) Integer page,
            @RequestParam(required = false) Integer rows,
            @RequestParam(required = false) String organId) {


        if (state == null) {
            state = new Integer(1);
        }

        if (organId == null) {
            organId = this.primaryOrganId;
        }

        Pagination<JobPrize> result = new Pagination<JobPrize>(page, rows);
        int startIdx = result.getStartIdx();

        int count = jobPrizeService.getResultSize(creatorId, state, organId);
        List<JobPrize> records = jobPrizeService.getResultInfo(creatorId, state, startIdx, rows, organId);

        result.setCount(count);
        result.setRecords(records);


        return result;
    }

    /**
     * 查询没有设过提成的职位
     */
    @RequestMapping(value = "/search_no_prize", method = RequestMethod.GET)
    public Pagination<Role> getRole(
            @RequestParam(required = false) List<String> organIds,
            @RequestParam(required = false) Integer page,
            @RequestParam(required = false) Integer rows
    ) {
        if (organIds == null) {
            organIds = this.organIds;
        }
        Pagination<Role> result = new Pagination<>(page, rows);
        List<Role> records = jobPrizeService.getRole(organIds);
        result.setRecords(records);
        return result;
    }


    /**
     * 查询所有设置过职位提成的员工
     *
     * @param page
     * @param rows
     * @param organId
     * @param params
     * @return
     */
    @RequestMapping(value = "/search_job", method = RequestMethod.GET)
    public Pagination<HashMap<String, Object>> getJobInfo(
            @RequestParam(required = false) Integer page,
            @RequestParam(required = false) Integer rows,
            @RequestParam(required = false) List<String> organId,
            @RequestParam(required = false) String params
    ) {
        if (organId == null) {
            organId = this.organIds;
        }


        Pagination<HashMap<String, Object>> result = new Pagination<HashMap<String, Object>>(page, rows);
        int startIdx = result.getStartIdx();

        int count = jobPrizeService.getJobSize(organId, params);
        List<UserRoles> info = jobPrizeService.getJobInfo(organId, params, startIdx, rows);

        /****** 解决 json 循环引用 不使用注解的方式
         * 接收在数组中
         * 然后 循环出来
         * 以 键值对 形式放入 map 中
         * 然后 返回数据
         *
         */
        List<HashMap<String, Object>> records = new ArrayList<>();
        for (int i = 0; i < info.size(); i++) {

            UserRoles userRoles = info.get(i);

            User user = userRoles.getUser();

            Role role = userRoles.getRole();

            HashMap<String, Object> keyValue = new HashMap<>();
            keyValue.put("roleId", role.getId());
            keyValue.put("roleName", role.getName());
            keyValue.put("userId", user.getId());
            keyValue.put("userName", user.getName());
            keyValue.put("id", userRoles.getId());
            records.add(keyValue);

        }

        result.setCount(count);
        result.setRecords(records);

        return result;
    }

}
